package org.antbook.embed;

import java.io.File;
import java.io.PrintStream;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.DemuxOutputStream;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class EmbeddedAnt {

    private Project project;
    private File _buildFile;

    public EmbeddedAnt(String buildFile) {
        _buildFile = new File(buildFile);
        System.out.println("Buildfile: " + _buildFile.getAbsolutePath());

        project = new Project();
        DefaultLogger logger = new DefaultLogger();
        project.addBuildListener(logger);
        logger.setOutputPrintStream(System.out);
        logger.setErrorPrintStream(System.err);
        logger.setMessageOutputLevel(Project.MSG_INFO);
        System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(project, true)));
    }

    public void executeTarget(String target) {
        try {
            project.init();
            project.fireBuildStarted();
            ProjectHelper helper = ProjectHelper.getProjectHelper();
            project.addReference("ant.projectHelper", helper);
            helper.parse(project, _buildFile);
            project.executeTarget(target);
            project.fireBuildFinished(null);
        } catch (BuildException e) {
            project.fireBuildFinished(e);
        }
    }

    public static void main(String args[]) {
        EmbeddedAnt embed = new EmbeddedAnt("build.xml");
        
        try {
            embed.executeTarget("default");
        } catch (BuildException e) {
            e.printStackTrace();
        }
    }
}